package com.chatplus.application.aiprocessor.platform.chat.xunfei;

import cn.bugstack.openai.executor.model.xunfei.config.XunFeiConfig;
import cn.bugstack.openai.executor.parameter.CompletionRequest;
import cn.bugstack.openai.session.Configuration;
import cn.bugstack.openai.session.OpenAiSessionFactory;
import cn.bugstack.openai.session.defaults.DefaultOpenAiSessionFactory;
import com.chatplus.application.aiprocessor.listener.CommonEventSourceListener;
import com.chatplus.application.aiprocessor.platform.chat.ChatProcessorService;
import com.chatplus.application.aiprocessor.provider.ChatAiProcessorServiceProvider;
import com.chatplus.application.common.constant.GroupCacheNames;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.common.util.CacheGroupUtils;
import com.chatplus.application.domain.dto.ChatConfigDto;
import com.chatplus.application.domain.dto.ws.ChatRecordMessage;
import com.chatplus.application.enumeration.AiPlatformEnum;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 讯飞 星火 机器人处理器
 *
 * @author chj
 * @date 2023/12/27
 **/
@Service(value = ChatAiProcessorServiceProvider.SERVICE_NAME_PRE + "XunFei")
public class XunFeiXhProcessor extends ChatProcessorService {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(XunFeiXhProcessor.class);

    @Override
    public void processStream() throws Exception {
        CompletionRequest request = getCompletionRequest();
        // 1. 创建参数
        ChatConfigDto.XunFeiSetting xunFeiSetting = CacheGroupUtils.get(GroupCacheNames.SYS_AI_SETTING, getChannel());
        if (xunFeiSetting != null) {
            request.setMaxTokens(xunFeiSetting.getMaxTokens());
            request.setTemperature(xunFeiSetting.getTemperature());
        }
        getSessionFactory().completions(request, new CommonEventSourceListener(chatRequest));
    }

    @Override
    public String processSync(List<ChatRecordMessage> messageContext) {
        return null;
    }

    @Override
    public AiPlatformEnum getChannel() {
        return AiPlatformEnum.XUN_FEI;
    }

    @Override
    public void initSessionFactory() {
        instance();
        // 需要用竖线（|）将 APPID, APIKey 和 APISecret 按照顺序串接起来填入
        OPEN_API_KEY_CACHE
                .forEach(item -> {
            String value = item.getApiKey();
            String appId = value.split("\\|")[0];
            String apiKey = value.split("\\|")[1];
            String secretKey = value.split("\\|")[2];
            XunFeiConfig xunFeiConfig = new XunFeiConfig();
            xunFeiConfig.setAppid(appId);
            xunFeiConfig.setApiKey(apiKey);
            xunFeiConfig.setApiHost(item.getUrl());
            xunFeiConfig.setApiSecret(secretKey);
            Configuration configuration = new Configuration();
            configuration.setLevel(HttpLoggingInterceptor.Level.BODY);
            configuration.setXunFeiConfig(xunFeiConfig);
            OpenAiSessionFactory factory = new DefaultOpenAiSessionFactory(configuration);
            OPEN_AI_SESSION_CACHE.put(getChannel(), factory.openSession());
        });
    }
}
